package com.coderworm.webscoketdemo.endpoint;

/**
 * @author: qiao.binbin@ustcinfo.com
 * @date: 2025/7/9 15:20
 * @version: 1.0
 * @description:
 */

import com.coderworm.webscoketdemo.service.WebSocketSessionService;

import com.coderworm.webscoketdemo.util.ApplicationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

@Slf4j
@Component
@ServerEndpoint("/ws/chat/{userId}")
public class ChatWebSocketEndpoint {

    private Session session;
    private String userId;

    @Resource
    private WebSocketSessionService webSocketSessionService;

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        webSocketSessionService = ApplicationUtil.getBean(WebSocketSessionService.class);
        webSocketSessionService.addSession(userId, session);
        log.info("User {} connected", userId);
    }

    @OnClose
    public void onClose() {
        webSocketSessionService.removeSession(userId);
        log.info("User {} disconnected", userId);
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("Received from {}: {}", userId, message);
        // 可以转发消息到其他用户或广播
        int ll = 1/0;
        webSocketSessionService.broadcast(message);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("Error in session {}", userId, throwable);
    }
}
